import json
import pandas as pd

global data
path = '../../../Data/douban.json'
with open(path, 'r', encoding='utf-8') as file:

    data = json.load(file)



def YearNumTop_5() -> tuple:
    '''
    :return: 发布电影次数最多的前五名年份以及电影次数
    '''
    years = []
    for movie in data:
        years.append(movie['year'][:4])

    # 统计数据出现的次数
    y = pd.Series(years)
    y_count = y.value_counts()   # value_counts函数会统计次数并且进行自动的排序，降序
    y_count = y_count.head(5)
    # print(y_count)
    x_list = y_count.index.tolist()   # 将索引转换为列表
    y_list = y_count.values.tolist()   # 将值转换为列表
    # print(x_list, y_list)
    return (x_list, y_list)


def TypeNum() -> tuple:
    '''
    :return: 电影类型及类型出现的次数
    '''
    types = []
    for type in data:
        types.extend(type['types'])
    # print(types)
    tp = pd.Series(types)
    tp = tp.value_counts()[1: -2]
    tp_label = tp.index.tolist()  # tolist用于将pandas中的Series或DataFrame转换为列表对象
    tp_count = tp.values.tolist()
    # print(tp_label, tp_count)
    return (tp_label, tp_count)


def YearMovies() -> tuple:
    '''
    :return: 年份，以及每一年的电影
    '''
    name = []
    year = []
    tree_dict = {}
    for movie in data:
        name.append(movie["name"])
        year.append(movie['year'])
    for n, y in zip(name, year):
        # print(z)
        # print(n, y)
        if tree_dict.get(y) is None:
            tree_dict[y] = [n]  # 如果键不存在，初始化为列表
        else:
            tree_dict[y].append(n)

    # 我们只取得前5年的数据
    keys_sliced = list(tree_dict.keys())[0: 5]
    tree_part = {key: tree_dict[key] for key in keys_sliced}
    # print(keys_sliced, tree_part)
    return (keys_sliced, tree_part)


def CountryNum() -> tuple:
    '''
    :return: 返回国家以及每个国家的电影数量
    '''
    country = []
    for movie in data:
        country.extend(movie['country'])
    # print(country)
    cou = pd.Series(country)
    cou_sort = cou.value_counts()
    country_ans = cou_sort.index.tolist()
    count_ans = cou_sort.values.tolist()
    # print(country_ans, count_ans)
    return (country_ans, count_ans)


if __name__ == '__main__':
    CountryNum()

